package com.example.android.BluetoothChat.service.impl;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.example.android.BluetoothChat.activity.PlayerListActivity;
import com.example.android.BluetoothChat.bean.Player;
import com.example.android.BluetoothChat.listener.NewPlayerFoundListener;
import com.example.android.BluetoothChat.util.factory.ComponentFactory;
import com.example.android.BluetoothChat.util.provider.player.impl.BluetoothPlayerProviderImpl;

public class BluetoothDiscoveryServiceImpl  extends ADiscoveryService implements NewPlayerFoundListener {

	public BluetoothDiscoveryServiceImpl() {

	}
	private ScheduledExecutorService scheduleTaskExecutor = null;

	final BluetoothPlayerProviderImpl playerProvider = new BluetoothPlayerProviderImpl();


	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		if(scheduleTaskExecutor == null){
			scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
			playerProvider.addNewPlayerFoundListener(this);
			playerProvider.findPlayersNearby(BluetoothDiscoveryServiceImpl.this);

			// This schedule a runnable task every 2 minutes
			scheduleTaskExecutor.scheduleAtFixedRate(new TimerTask() {
				
				@Override
			  public void run() {
					playerProvider.findPlayersNearby(BluetoothDiscoveryServiceImpl.this);
			  }
			}, 30, 30, TimeUnit.SECONDS);
			// We want this service to continue running until it is explicitly
			// stopped, so return sticky.
		}
		return START_STICKY;
	}


	@Override
	public boolean stopService(Intent service){
		super.stopService(service);
		scheduleTaskExecutor.shutdown();
		playerProvider.unregisterResources(this);
		return true;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public void newPlayerFound(Player parPlayer) {
		ComponentFactory.createNewPlayerNotification(this, parPlayer);
		
	}

}
